<!--
  功能：选择图片弹层
  时间：2023年03月06日 17:38:14
-->
<template>
  <el-dialog
    v-model="props.modelValue"
    title="选择图片"
    width="80%"
    draggable
    :before-close="close"
  >
    <div class="an-img">
      <div class="flex v1">
        <el-image
          class="v2"
          v-for="(v, i) in pageData.list"
          :key="i"
          @click="successImg(v.key)"
          :src="config.serverImg + v.key"
          fit="contain"
        ></el-image>
      </div>
    </div>
    <template #footer>
      <div class="flex footer">
        <div>
          <el-pagination
            background
            @current-change="switchCurrentChange"
            v-model:currentPage="pageData.page"
            :default-page-size="pageData.limit"
            layout="total,prev, pager, next"
            :total="pageData.total"
          >
          </el-pagination>
        </div>
        <div class="flex">
          <!-- 多图上传组件 -->
          <upImg @img="getList()" />

          <!-- 图片裁剪组件 -->
          <cropper-img @img="successImg" />

          <el-button @click="close">取消</el-button>
          <el-button @click="router.push('/img')">管理图片</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { cropperImg, upImg } from "@/components/upImg";
import { post } from "@/common/http";
import config from "@/common/config";

const router = useRouter();

const emit = defineEmits<{
  (e: "update:modelValue", data: boolean): void; //向父组件更新 弹窗是否显示
  (e: "getImg", data?: { imgUrl: string }): void; //向父组件传递 已选择的图片
}>();

const props = defineProps({
  //是否显示
  modelValue: {
    type: Boolean,
    required: true,
    default: false,
  },
});

// 页面数据
const pageData = reactive<any>({
  list: [], //图片列表
  spaceList: "",
  total: 0,
  page: 1,
  limit: 39,
  selectIndex: -1,
  selectValue: null,
});

onMounted(() => {
  getList();
});

//图片列表
function getList() {
  post("api/Img/get_list", {
    prefix: "local",
    page: pageData.page,
    limit: pageData.limit,
  }).then((res) => {
    pageData.list = res.data.list;
    pageData.total = res.total;
  });
}

//关闭弹窗
function close() {
  emit("update:modelValue", false);
}

// 点击分页
function switchCurrentChange(val: number) {
  console.log(`当前页: ${val}`);
  getList();
}

//接收组件上传图片成功状态
//裁剪模式，直接默认选择图片，多图模式需要自行选择图片
function successImg(data: any) {
  emit("update:modelValue", false);
  emit("getImg", {
    imgUrl: data,
  });
}
</script>
<style scoped lang="scss">
.v1 {
  flex-wrap: wrap;
}
.v2 {
  border: 1px solid #f1f1f1;
  width: 80px;
  height: 80px;
  border-radius: 5px;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  &:hover {
    border-color: var(--el-color-primary);
  }

  &:nth-child(13n) {
    margin-right: 0;
  }
}

.footer {
  justify-content: space-between;
}
</style>
